package cn.chaozhoubang.vmall.backend.controller.impl;

import cn.chaozhoubang.vmall.backend.annotation.AuthRequire;
import cn.chaozhoubang.vmall.backend.controller.UserController;
import cn.chaozhoubang.vmall.backend.mapper.ManagerMapper;
import cn.chaozhoubang.vmall.backend.mapper.OrderMapper;
import cn.chaozhoubang.vmall.backend.mapper.RoleMapper;
import cn.chaozhoubang.vmall.backend.model.SpManager;
import cn.chaozhoubang.vmall.backend.model.SpOrder;
import cn.chaozhoubang.vmall.backend.model.SpRole;
import cn.chaozhoubang.vmall.backend.model.SpUser;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.catalina.Manager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.management.relation.Role;
import java.util.List;

@RestController
@RequestMapping("/api/private/v1")
public class UserControllerImpl implements UserController {

    private ManagerMapper managerMapper;
    private RoleMapper roleMapper;

    private JSONArray buildUsers(List<SpManager> managers){
        JSONArray array = new JSONArray();
        for(SpManager manager: managers){
            final JSONObject json =new JSONObject();
            final QueryWrapper<SpRole> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id",manager.getRoleId());
            SpRole role =roleMapper.selectOne(wrapper);
            json.set("username",manager.getMgName())
                    .set("id",manager.getMgId())
                    .set("email",manager.getMgEmail())
                    .set("mobile",manager.getMgMobile())
                    .set("role_name", role == null? "未知角色": role.getRoleName())
                    .set("mg_state",manager.getMgState() == 1);
            array.add(json);
        }
        return array;
    }
    private JSONObject buildMeta(int status, String msg) {
        final JSONObject meta = new JSONObject();
        meta.set("status", status);
        meta.set("msg", msg);
        return meta;
    }
    private JSONObject buildData(IPage<SpManager> page) {
        final JSONObject data = new JSONObject();
        data.set("total", page.getTotal());
        data.set("pagenum", page.getCurrent());
        data.set("users",buildUsers(page.getRecords()));

        return data;
    }
    private JSONObject buildResult(JSONObject meta, JSONObject data) {
        final JSONObject res = new JSONObject();
        res.set("meta", meta);
        res.set("data", data);
        return res;
    }


    @Override
    @AuthRequire
    @GetMapping(value = "/users",produces = "application/json;charset=UTF-8")
    public String getUser(@RequestParam(value = "query", required = false, defaultValue = "") String query, int pagenum, int pagesize) {
        Page<SpManager> page = new Page<>(pagenum, pagesize);
        IPage<SpManager> paging = null;
        if(!"".equals(query)) {
            final QueryWrapper<SpManager> wrapper = new QueryWrapper<>();
            wrapper.like("mg_name", "%" + query + "%");
            paging = managerMapper.selectPage(page, wrapper);
        } else paging = managerMapper.selectPage(page, null);
        final JSONObject data = buildData(paging);
        final JSONObject meta = buildMeta(200, "获取成功");
        return buildResult(meta, data).toString();
    }

    @Override
    @AuthRequire
    @PostMapping(value = "/users",produces = "application/json;charset=UTF-8")
    public String addUser(@RequestBody SpManager manager) {
        manager.setMgPwd(DigestUtil.md5Hex(manager.getMgPwd()));
        final int rs = managerMapper.insert(manager);
        if(rs>0){
            return buildResult(buildMeta(201, "插入成功"), new JSONObject()).toString();
        }
        return buildResult(buildMeta(500, "插入失败"), new JSONObject()).toString();
    }

    @Override
    @GetMapping(value = "/users/{id}",produces = "application/json;charset=UTF-8")
    public String getManager(@PathVariable int id){
        final JSONObject data = new JSONObject();
        final QueryWrapper<SpManager> managerQueryWrapper = new QueryWrapper<>();
        managerQueryWrapper.eq("mg_id", id);
        SpManager manager = managerMapper.selectOne(managerQueryWrapper);
        data.set("id",manager.getMgId())
                .set("rid",manager.getRoleId())
                .set("username",manager.getMgName())
                .set("mobile",manager.getMgMobile())
                .set("email",manager.getMgEmail())
                .set("mg_state",manager.getMgState());
        return buildResult(buildMeta(200, "获取成功"), data).toString();
    }
    @Override
    @PutMapping(value = "/users/{id}", produces = "application/json;charset=UTF-8")
    public String putManager(@RequestBody SpManager manager,@PathVariable int id){
        if(manager ==null)
            return buildResult(buildMeta(400,"bad request"),new JSONObject()).toString();
        System.out.println(manager);
        final UpdateWrapper<SpManager> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("mg_mobile", manager.getMgMobile());
        updateWrapper.set("mg_email", manager.getMgEmail());
        updateWrapper.eq("mg_id", id);
        final int rs = managerMapper.update(null, updateWrapper);
        if(rs>0){
            JSONObject data =new JSONObject();
            data.set("id",manager.getMgId())
                    .set("email",manager.getMgEmail())
                    .set("mobile",manager.getMgMobile())
                    .set("username",manager.getMgName())
                    .set("role_id",manager.getRoleId());
            return buildResult(buildMeta(200, "修改成功"), data).toString();
        }
        return buildResult(buildMeta(500, "修改失败"), new JSONObject()).toString();
    }

    @Override
    @PutMapping(value = "/users/{id}/state/{state}", produces = "application/json;charset=UTF-8")
    public String updateState(@PathVariable int id, @PathVariable String state) {
        final UpdateWrapper<SpManager> wrapper = new UpdateWrapper<>();
        wrapper.eq("mg_id", id);
        if("true".equals(state)) wrapper.set("mg_state", 1);
        else wrapper.set("mg_state", 0);
        final int rs = managerMapper.update(null, wrapper);
        if(rs>0){
            return buildResult(buildMeta(200, "设置状态成功"), new JSONObject()).toString();
        }
        return buildResult(buildMeta(500, "设置状态失败"), new JSONObject()).toString();
    }

    @Override
    @DeleteMapping(value = "/users/{id}",produces = "application/json;charset=UTF-8")
    public String DeleteManager (@PathVariable int id){
        final  int rs= managerMapper.deleteById(id);
        if(rs>0) {
            return buildResult(buildMeta(200, "删除成功"), new JSONObject()).toString();
        }
        return buildResult(buildMeta(500, "删除失败"), new JSONObject()).toString();
        }


    @Autowired
    public void setManagerMapper(ManagerMapper managerMapper) {
        this.managerMapper = managerMapper;
    }
    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }
}
